
import React, { useState, useEffect, useRef } from 'react';

interface EditableTextProps {
  initialValue: string; // This will now typically be the string to edit (e.g. JSON string for objects)
  onSave: (value: string) => void;
  label?: string;
  isTextArea?: boolean;
  className?: string;
  inputClassName?: string;
  textClassName?: string; // Applied to the wrapper when not editing
  disabled?: boolean;
  children?: React.ReactNode; // For custom display when not editing
}

const PencilIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" {...props}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10" />
  </svg>
);

const EditableText: React.FC<EditableTextProps> = ({
  initialValue,
  onSave,
  label,
  isTextArea = false,
  className = '',
  inputClassName = 'bg-gray-700 text-gray-100 p-2 rounded w-full focus:ring-2 focus:ring-blue-500 outline-none',
  textClassName = 'p-2 hover:bg-gray-700 rounded cursor-pointer transition-colors',
  disabled = false,
  children
}) => {
  const [isEditing, setIsEditing] = useState(false);
  const [currentEditValue, setCurrentEditValue] = useState(initialValue);
  const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement>(null);

  useEffect(() => {
    setCurrentEditValue(initialValue);
  }, [initialValue]);

  useEffect(() => {
    if (isEditing && inputRef.current) {
      inputRef.current.focus();
      if (inputRef.current instanceof HTMLTextAreaElement) {
        inputRef.current.style.height = 'auto';
        inputRef.current.style.height = `${inputRef.current.scrollHeight}px`;
      }
    }
  }, [isEditing]);

  const handleSave = () => {
    // Only call onSave if value actually changed (trimming for comparison)
    if (currentEditValue.trim() !== initialValue.trim()) {
      onSave(currentEditValue); // Send back the potentially trimmed or untrimmed value based on currentEditValue
    }
    setIsEditing(false);
  };

  const handleCancel = () => {
    setCurrentEditValue(initialValue); // Reset to original initialValue before edit
    setIsEditing(false);
  }

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !isTextArea && !e.shiftKey) {
      e.preventDefault();
      handleSave();
    } else if (e.key === 'Escape') {
      handleCancel();
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setCurrentEditValue(e.target.value);
    if (isTextArea && e.target instanceof HTMLTextAreaElement) {
        e.target.style.height = 'auto';
        e.target.style.height = `${e.target.scrollHeight}px`;
    }
  }

  if (disabled) {
    return (
        <div className={`${className} ${textClassName} opacity-70 cursor-not-allowed`}>
            {children || currentEditValue || (isTextArea ? '无内容' : '未设置')}
        </div>
    );
  }

  if (isEditing) {
    return (
      <div className={`w-full ${className}`}>
        {label && <label className="block text-sm font-medium text-gray-400 mb-1">{label}</label>}
        {isTextArea ? (
          <textarea
            ref={inputRef as React.RefObject<HTMLTextAreaElement>}
            value={currentEditValue}
            onChange={handleInputChange}
            onBlur={handleSave} // Save on blur
            onKeyDown={handleKeyDown}
            className={`${inputClassName} min-h-[80px] resize-y`}
            rows={3}
          />
        ) : (
          <input
            ref={inputRef as React.RefObject<HTMLInputElement>}
            type="text"
            value={currentEditValue}
            onChange={handleInputChange}
            onBlur={handleSave} // Save on blur
            onKeyDown={handleKeyDown}
            className={inputClassName}
          />
        )}
      </div>
    );
  }

  // Not editing: display children if provided, otherwise the initialValue (or placeholder)
  const displayContent = children ? children : (
    initialValue || (isTextArea ? '点击编辑内容...' : '点击编辑...')
  );
  
  const displayTextClass = children ? '' : (initialValue ? '' : 'text-gray-500');


  return (
    <div className={`relative group ${className} ${textClassName}`} onClick={() => setIsEditing(true)}>
      {label && <label className="block text-sm font-medium text-gray-400 mb-1">{label}</label>}
      <span className={displayTextClass}>
        {displayContent}
      </span>
      {!disabled && <PencilIcon className="w-4 h-4 text-gray-500 absolute top-1/2 right-2 transform -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity" />}
    </div>
  );
};

export default EditableText;
